package artid.com.arttogo.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.bean.CropperImage;
import android.camera.BeepManager;
import android.camera.CameraManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.decoding.CaptureActivityHandler;
import android.decoding.InactivityTimer;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.Utils;
import android.view.CropImageView;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewfinderView;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.ResultMetadataType;
import com.google.zxing.ResultPoint;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Map;
import java.util.Vector;

import artid.com.arttogo.R;
import artid.com.arttogo.utils.BitmapUtil;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.ToastUtil;


/**
 * 条码二维码扫描功能实现
 */
public class CaptureActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = CaptureActivity.class.getSimpleName();
    private Context mContext;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private View bgRL;
    private RelativeLayout scanRL, photographRL;
    private TextView backBtn, flashLampBtn, tab_scanBtn, tab_identifyImagesBtn, tab_photographBtn,
            sweepRecordBtn, submit, albumBtn, distinguishHint;
    private int maxCamera = 2;//最多几个相机主要是为了选择变色和whichActivity是同步的
    private int whichActivity = 0;//默认我的出售 （0：扫一扫 1：识图 2:拍图）
    private Boolean FirstBootScan = true;//判断是否第一次启动扫描(默认为ture)
    private Boolean isFlash = false;//闪光灯默认关闭
    private LinearLayout tabLL;
    private String[] labelData = new String[]{"扫码", "扫图", "拍图"};

    //=========================== 扫一扫变量声明开始 =============================//
    private boolean hasSurface;
    private BeepManager beepManager;// 声音震动管理器。如果扫描成功后可以播放一段音频，也可以震动提醒，可以通过配置来决定扫描成功后的行为。
    public SharedPreferences mSharedPreferences;// 存储二维码条形码选择的状态
    public static String currentState;// 条形码二维码选择状态
    private String characterSet;
    private ViewfinderView viewfinderView;
    /**
     * 活动监控器，用于省电，如果手机没有连接电源线，那么当相机开启后如果一直处于不被使用状态则该服务会将当前activity关闭。
     * 活动监控器全程监控扫描活跃状态，与CaptureActivity生命周期相同.每一次扫描过后都会重置该监控，即重新倒计时。
     */
    private InactivityTimer inactivityTimer;
    private CameraManager cameraManager;
    private Vector<BarcodeFormat> decodeFormats;// 编码格式
    private CaptureActivityHandler mHandler;// 解码线程
    private static final Collection<ResultMetadataType> DISPLAYABLE_METADATA_TYPES = EnumSet
            .of(ResultMetadataType.ISSUE_NUMBER,
                    ResultMetadataType.SUGGESTED_PRICE,
                    ResultMetadataType.ERROR_CORRECTION_LEVEL,
                    ResultMetadataType.POSSIBLE_COUNTRY);
    //=========================== 扫一扫变量声明结束 =============================//

    //=========================== 拍图量声明开始 =============================//
    private static int Degrees;//要旋转的图片角度
    private LinearLayout cropperLL;//剪裁布局
    private View cropimageviewRL;
    private CropImageView mCropImageView;//剪裁View
    private TextView photographCancelBtn, photographCompleteBtn;
    private String path = Environment.getExternalStorageDirectory() + "/YJB_C/CustomCameraImage.png";
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    //=========================== 拍图量声明结束 =============================//
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initSetting();
        setContentView(R.layout.activity_capture);
        initView();
        if (whichActivity == 0) {
            //初始化扫描
            initScan();
        }
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    /**
     * 初始化窗口设置
     */
    private void initSetting() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 保持屏幕处于点亮状态
        // window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); // 全屏
//        requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题栏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 竖屏
    }

    private void initView() {
        mContext = CaptureActivity.this;
        bgRL = (View) findViewById(R.id.Capture_bg);
        surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        //监听左右滑动事件
        surfaceView.setLongClickable(true);
        surfaceView.setOnTouchListener(new MyGestureListener(this));
        tabLL = (LinearLayout) findViewById(R.id.Capture_tabLL);
        tab_scanBtn = (TextView) findViewById(R.id.Capture_tab_scanBtn);
        tab_scanBtn.setOnClickListener(this);
        tab_identifyImagesBtn = (TextView) findViewById(R.id.Capture_tab_identifyImagesBtn);
        tab_identifyImagesBtn.setOnClickListener(this);
        tab_photographBtn = (TextView) findViewById(R.id.Capture_tab_photographBtn);
        tab_photographBtn.setOnClickListener(this);
        scanRL = (RelativeLayout) findViewById(R.id.Capture_scanRL);
        backBtn = (TextView) findViewById(R.id.Capture_backBtn);
        backBtn.setOnClickListener(this);
        flashLampBtn = (TextView) findViewById(R.id.Capture_flashLampBtn);
        flashLampBtn.setOnClickListener(this);
        sweepRecordBtn = (TextView) findViewById(R.id.Capture_sweepRecordBtn);
        sweepRecordBtn.setOnClickListener(this);
        photographRL = (RelativeLayout) findViewById(R.id.Capture_photographRL);
        cropimageviewRL = (View) findViewById(R.id.Capture_cropimageviewRL);
        submit = (TextView) findViewById(R.id.Capture_submit);
        submit.setOnClickListener(this);
        photographCancelBtn = (TextView) findViewById(R.id.Capture_photographCancelBtn);
        photographCancelBtn.setOnClickListener(this);
        photographCompleteBtn = (TextView) findViewById(R.id.Capture_photographCompleteBtn);
        photographCompleteBtn.setOnClickListener(this);
        cropperLL = (LinearLayout) findViewById(R.id.Capture_cropperLL);
        mCropImageView = (CropImageView) findViewById(R.id.Capture_cropimageview);
        mCropImageView.setGuidelines(2);
        albumBtn = (TextView) findViewById(R.id.Capture_albumBtn);
        albumBtn.setOnClickListener(this);
        distinguishHint = (TextView) findViewById(R.id.Capture_distinguishHint);
        FirstBootScan = false;
        initComponent();
        selectTab(whichActivity);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.Capture_backBtn:
                finish();
                break;
            case R.id.Capture_sweepRecordBtn:
                //扫码记录
                intent = new Intent(CaptureActivity.this, QRCodeHistoryActivity.class);
                startActivity(intent);
                break;
            case R.id.Capture_flashLampBtn:
                //闪光灯
                openflash();
                break;
            case R.id.Capture_tab_scanBtn:
                //扫码Tab按钮
                selectTab(0);
                break;
            case R.id.Capture_tab_identifyImagesBtn:
                //识图Tab按钮
                selectTab(1);
                break;
            case R.id.Capture_tab_photographBtn:
                //拍图Tab按钮
                selectTab(2);
                break;
            case R.id.Capture_submit:
                //拍照按钮
                TakePhoto();
                break;
            case R.id.Capture_photographCancelBtn:
                //剪裁之后取消
                cameraManager.restartPreview();
                cropperLL.setVisibility(View.GONE);
                break;
            case R.id.Capture_photographCompleteBtn:
                //剪裁之后确定
                getCutImage();
                break;
            case R.id.Capture_albumBtn:
                //相册
                intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");// 相片类型
                startActivityForResult(intent, 1);
                break;

            default:
                break;
        }
    }

    /**
     * 初始化扫描
     */
    private void initScan() {
        //initComponent();
        photographRL.setVisibility(View.GONE);
        distinguishHint.setVisibility(View.GONE);
        scanRL.setVisibility(View.VISIBLE);
        sweepRecordBtn.setVisibility(View.VISIBLE);
        sweepRecordBtn.setOnClickListener(this);
    }

    /**
     * 初始化拍照
     */
    private void initPhotograph() {
        sweepRecordBtn.setVisibility(View.GONE);
        scanRL.setVisibility(View.GONE);
        distinguishHint.setVisibility(View.GONE);
        photographRL.setVisibility(View.VISIBLE);
    }

    /**
     * 初始图片识别
     */
    private void IdentifyImages() {
        sweepRecordBtn.setVisibility(View.GONE);
        scanRL.setVisibility(View.GONE);
        photographRL.setVisibility(View.GONE);
        distinguishHint.setVisibility(View.VISIBLE);
    }

    /**
     * 更改选择的Tab标签颜色与图案
     */
    public void setTextViewDrawableTop() {
        Resources res = getResources();
        Drawable img_off = res.getDrawable(R.drawable.ico_point);
        //调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
        img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
        tab_scanBtn.setTextColor(Color.parseColor("#ffffff"));
        tab_identifyImagesBtn.setTextColor(Color.parseColor("#ffffff"));
        tab_photographBtn.setTextColor(Color.parseColor("#ffffff"));
        tab_scanBtn.setCompoundDrawables(null, null, null, null);
        tab_identifyImagesBtn.setCompoundDrawables(null, null, null, null);
        tab_photographBtn.setCompoundDrawables(null, null, null, null);
        switch (whichActivity) {
            case 0:
                tab_scanBtn.setTextColor(Color.parseColor("#FFC000"));
                tab_scanBtn.setCompoundDrawables(null, img_off, null, null); //设置上图标
                break;
            case 1:
                tab_identifyImagesBtn.setTextColor(Color.parseColor("#FFC000"));
                tab_identifyImagesBtn.setCompoundDrawables(null, img_off, null, null); //设置上图标
                break;
            case 2:
                tab_photographBtn.setTextColor(Color.parseColor("#FFC000"));
                tab_photographBtn.setCompoundDrawables(null, img_off, null, null); //设置上图标
                break;
            default:
                break;
        }

    }

    /**
     * 选择的标签
     */
    public void selectTab(int selectTab) {
        startTranslation();
        whichActivity = selectTab;
        setTextViewDrawableTop();
        switch (whichActivity) {
            case 0:
                initScan();
                break;
            case 1:
                IdentifyImages();
                break;
            case 2:
                initPhotograph();
                break;

            default:
                break;
        }
    }


    /**
     * 主要对相机进行初始化工作
     */
    @Override
    protected void onResume() {
        super.onResume();
        startCamera();
    }


    /**
     * 暂停活动监控器,关闭摄像头
     */
    @Override
    protected void onPause() {
        closeCamera();
        super.onPause();
    }

    /**
     * 停止活动监控器,保存最后选中的扫描类型
     */
    @Override
    protected void onDestroy() {
        closeCamera();
        super.onDestroy();
    }

    /**
     * 启动相机
     */
    private void startCamera() {
        if (whichActivity == 0 || whichActivity == 2) {
            //扫一扫
            inactivityTimer.onActivity();
            viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
            // viewfinderView.setCameraManager(cameraManager);
            surfaceHolder = surfaceView.getHolder();
            setScanType();
            resetStatusView();
            if (hasSurface) {
                initCamera(surfaceHolder);
            } else {
                // 如果SurfaceView已经渲染完毕，会回调surfaceCreated，在surfaceCreated中调用initCamera()
                surfaceHolder.addCallback(surfaceScanCallback);
            }
            // 加载声音配置，其实在BeemManager的构造器中也会调用该方法，即在onCreate的时候会调用一次
            beepManager.updatePrefs();
            // 恢复活动监控器
            inactivityTimer.onResume();
        }
    }

    /**
     * 关闭相机
     */
    private void closeCamera() {
        if (whichActivity != 0 || whichActivity != 2) {
            inactivityTimer.shutdown();
            saveScanTypeToSp();
            if (mHandler != null) {
                mHandler.quitSynchronously();
                mHandler = null;
            }
            // 暂停活动监控器
            inactivityTimer.onPause();
            // 关闭摄像头
            cameraManager.closeDriver();
            if (!hasSurface) {
                SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
                SurfaceHolder surfaceHolder = surfaceView.getHolder();
                surfaceHolder.removeCallback(surfaceScanCallback);
            }
            hasSurface = true;
        }
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Capture Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    //==============================监听手指左右滑动开始=====================================//

    /**
     * 实现监听左右滑动的事件，哪个view需要的时候直接setOnTouchListener就可以用了
     *
     * @author LinZhiquan
     */
    public class GestureListener extends SimpleOnGestureListener implements OnTouchListener {
        /**
         * 左右滑动的最短距离
         */
        private int distance = 100;
        /**
         * 左右滑动的最大速度
         */
        private int velocity = 200;

        private GestureDetector gestureDetector;

        public GestureListener(Context context) {
            super();
            gestureDetector = new GestureDetector(context, this);
        }

        /**
         * 向左滑的时候调用的方法，子类应该重写
         *
         * @return
         */
        public boolean left() {
            return false;
        }

        /**
         * 向右滑的时候调用的方法，子类应该重写
         *
         * @return
         */
        public boolean right() {
            return false;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            // TODO Auto-generated method stub
            // e1：第1个ACTION_DOWN MotionEvent
            // e2：最后一个ACTION_MOVE MotionEvent
            // velocityX：X轴上的移动速度（像素/秒）
            // velocityY：Y轴上的移动速度（像素/秒）
            // 向左滑
            if (e1.getX() - e2.getX() > distance
                    && Math.abs(velocityX) > velocity) {
                left();
            }
            // 向右滑
            if (e2.getX() - e1.getX() > distance
                    && Math.abs(velocityX) > velocity) {
                right();
            }
            return false;
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            gestureDetector.onTouchEvent(event);
            return false;
        }

        public int getDistance() {
            return distance;
        }

        public void setDistance(int distance) {
            this.distance = distance;
        }

        public int getVelocity() {
            return velocity;
        }

        public void setVelocity(int velocity) {
            this.velocity = velocity;
        }

        public GestureDetector getGestureDetector() {
            return gestureDetector;
        }

        public void setGestureDetector(GestureDetector gestureDetector) {
            this.gestureDetector = gestureDetector;
        }
    }

    /**
     * 继承GestureListener，重写left和right方法
     */
    private class MyGestureListener extends GestureListener {
        public MyGestureListener(Context context) {
            super(context);
        }

        @Override
        public boolean left() {
            if (whichActivity != 0) {
                whichActivity = whichActivity - 1;
            } else {
                whichActivity = maxCamera;
            }
            selectTab(whichActivity);
            return super.left();
        }

        @Override
        public boolean right() {
            if (whichActivity != maxCamera) {
                whichActivity = whichActivity + 1;
            } else {
                whichActivity = 0;
            }
            selectTab(whichActivity);
            return super.right();
        }
    }

    //==============================监听手指左右滑动结束=====================================//


    //==============================扫描代码开始=====================================//

    /**
     * 初始化功能组件
     */
    private void initComponent() {
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        currentState = this.mSharedPreferences.getString("currentState", "qrcode");
        cameraManager = new CameraManager(getApplication(), CaptureActivity.this);
    }

    // /**
    // * 初始化点击切换扫描类型事件
    // */
    // private void initEvent() {
    // onecode.setOnClickListener(this.onecodeImageListener);
    // qrcode.setOnClickListener(this.qrcodeImageListener);
    // qrcode.setSelected(true);
    // }

    /**
     * 初始设置扫描类型（最后一次使用类型）
     */
    private void setScanType() {
        do {
            if ((CaptureActivity.currentState != null)
                    && (CaptureActivity.currentState.equals("onecode"))) {
                // qrcode.setBackgroundResource(R.drawable.scan_qr);
                // onecode.setBackgroundResource(R.drawable.scan_store_hl);
                // qrcode.setSelected(false);
                // onecode.setSelected(true);
                viewfinderView.setVisibility(View.VISIBLE);
                onecodeSetting();
                // statusView.setText(R.string.scan_onecode);
                return;
            }
        }

        while ((CaptureActivity.currentState == null)
                || (!CaptureActivity.currentState.equals("qrcode")));
        // onecode.setBackgroundResource(R.drawable.scan_store);
        // qrcode.setBackgroundResource(R.drawable.scan_qr_hl);
        // qrcode.setSelected(true);
        // onecode.setSelected(false);
        viewfinderView.setVisibility(View.VISIBLE);
        qrcodeSetting();
        // statusView.setText(R.string.scan_qrcode);
    }


    /**
     * 展示状态视图和扫描窗口，隐藏结果视图
     */
    private void resetStatusView() {
        // resultView.setVisibility(View.GONE);
        // statusView.setVisibility(View.GONE);
        viewfinderView.setVisibility(View.VISIBLE);
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    /**
     * 初始化摄像头。打开摄像头，检查摄像头是否被开启及是否被占用
     *
     * @param surfaceHolder
     */
    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            Log.w(TAG,
                    "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the mHandler starts the preview, which can also throw a
            // RuntimeException.
            if (mHandler == null) {
                // mHandler = new CaptureActivityHandler(this, decodeFormats,
                // characterSet, cameraManager);
                mHandler = new CaptureActivityHandler(this, decodeFormats,
                        characterSet, cameraManager);
            }
            // decodeOrStoreSavedBitmap(null, null);
        } catch (IOException ioe) {
            Log.w(TAG, "打开相机错误："+ioe.toString());
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
            Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }
    }

    /**
     * 若摄像头被占用或者摄像头有问题则跳出提示对话框
     */
    private void displayFrameworkBugMessageAndExit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage("请设置开启摄像头权限");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                NetUtils.getAppDetailSettingIntent(mContext);
            }
        });
        builder.show();
    }






    /**
     * 保存退出进程前选中的二维码条形码的状态
     */
    private void saveScanTypeToSp() {
        SharedPreferences.Editor localEditor = this.mSharedPreferences.edit();
        localEditor.putString("currentState", CaptureActivity.currentState);
        localEditor.commit();
    }

    /**
     * 获取扫描结果
     *
     * @param rawResult
     * @param barcode
     * @param scaleFactor
     */
    public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
        inactivityTimer.onActivity();

        boolean fromLiveScan = barcode != null;
        if (fromLiveScan) {

            // Then not from history, so beep/vibrate and we have an image to
            // draw on
            beepManager.playBeepSoundAndVibrate();
            drawResultPoints(barcode, scaleFactor, rawResult);
        }
        DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT,
                DateFormat.SHORT);
        Map<ResultMetadataType, Object> metadata = rawResult
                .getResultMetadata();
        StringBuilder metadataText = new StringBuilder(20);
        if (metadata != null) {
            for (Map.Entry<ResultMetadataType, Object> entry : metadata
                    .entrySet()) {
                if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
                    metadataText.append(entry.getValue()).append('\n');
                }
            }
            if (metadataText.length() > 0) {
                metadataText.setLength(metadataText.length() - 1);
            }
        }
        Intent intent = new Intent(CaptureActivity.this, ScanCertiActivity.class);
        intent.putExtra("code", rawResult.getText());
        startActivity(intent);
        restartPreviewAfterDelay(3000);
        finish();
        // handleDecodeInternally(rawResult, barcode);

    }

    /**
     * 在扫描图片结果中绘制绿色的点
     *
     * @param barcode
     * @param scaleFactor
     * @param rawResult
     */
    private void drawResultPoints(Bitmap barcode, float scaleFactor,
                                  Result rawResult) {
        ResultPoint[] points = rawResult.getResultPoints();
        if (points != null && points.length > 0) {
            Canvas canvas = new Canvas(barcode);
            Paint paint = new Paint();
            paint.setColor(getResources().getColor(R.color.result_points));
            if (points.length == 2) {
                paint.setStrokeWidth(4.0f);
                drawLine(canvas, paint, points[0], points[1], scaleFactor);
            } else if (points.length == 4
                    && (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || rawResult
                    .getBarcodeFormat() == BarcodeFormat.EAN_13)) {
                drawLine(canvas, paint, points[0], points[1], scaleFactor);
                drawLine(canvas, paint, points[2], points[3], scaleFactor);
            } else {
                paint.setStrokeWidth(10.0f);
                for (ResultPoint point : points) {
                    if (point != null) {
                        canvas.drawPoint(scaleFactor * point.getX(),
                                scaleFactor * point.getY(), paint);
                    }
                }
            }
        }
    }

    /**
     * 在扫描图片结果中绘制绿色的线
     *
     * @param canvas
     * @param paint
     * @param a
     * @param b
     * @param scaleFactor
     */
    private static void drawLine(Canvas canvas, Paint paint, ResultPoint a,
                                 ResultPoint b, float scaleFactor) {
        if (a != null && b != null) {
            canvas.drawLine(scaleFactor * a.getX(), scaleFactor * a.getY(),
                    scaleFactor * b.getX(), scaleFactor * b.getY(), paint);
        }
    }


    /**
     * 点击响应条形码扫描
     */
    private OnClickListener onecodeImageListener = new OnClickListener() {
        public void onClick(View paramAnonymousView) {

            // qrcode.setBackgroundResource(R.drawable.scan_qr);
            // onecode.setBackgroundResource(R.drawable.scan_store_hl);
            // qrcode.setSelected(false);
            // onecode.setSelected(true);
            // statusView.setText(R.string.scan_onecode);
            viewfinderView.setVisibility(View.VISIBLE);
            currentState = "onecode";
            onecodeSetting();

        }
    };

    private void onecodeSetting() {
        decodeFormats = new Vector<BarcodeFormat>(7);
        decodeFormats.clear();
        // decodeFormats.addAll(DecodeThread.ONE_D_FORMATS);
        // scanTextView.setText(R.string.scan_one);
        if (null != mHandler) {
            mHandler.setDecodeFormats(decodeFormats);
        }

        viewfinderView.refreshDrawableState();
        // cameraManager.setManualFramingRect(700, 00);
        viewfinderView.refreshDrawableState();

    }

    /**
     * 点击响应二维码扫描
     */
    private OnClickListener qrcodeImageListener = new OnClickListener() {
        public void onClick(View paramAnonymousView) {

            // onecode.setBackgroundResource(R.drawable.scan_store);
            // qrcode.setBackgroundResource(R.drawable.scan_qr_hl);
            // qrcode.setSelected(true);
            // onecode.setSelected(false);
            // statusView.setText(R.string.scan_qrcode);
            viewfinderView.setVisibility(View.VISIBLE);
            currentState = "qrcode";
            qrcodeSetting();

        }
    };

    private void qrcodeSetting() {
        decodeFormats = new Vector<BarcodeFormat>(2);
        decodeFormats.clear();
        decodeFormats.add(BarcodeFormat.QR_CODE);
        decodeFormats.add(BarcodeFormat.DATA_MATRIX);
        // scanTextView.setText(R.string.scan_qr);
        if (null != mHandler) {
            mHandler.setDecodeFormats(decodeFormats);
        }

        viewfinderView.refreshDrawableState();
        //		cameraManager.setManualFramingRect(300, 300);
        viewfinderView.refreshDrawableState();
    }

    SurfaceHolder.Callback surfaceScanCallback = new SurfaceHolder.Callback() {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            if (holder == null) {
                Log.e(TAG,
                        "*** WARNING *** surfaceCreated() gave us a null surface!");
            }
            if (!hasSurface) {
                hasSurface = true;
                initCamera(holder);
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            hasSurface = false;
        }

    };


    /**
     * 闪光灯调节器。自动检测环境光线强弱并决定是否开启闪光灯
     */
    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return mHandler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    /**
     * 闪光灯开关
     */
    private void openflash() {
        if (cameraManager != null) {
            if (isFlash) {
                cameraManager.setFlash(false);
                flashLampBtn.setBackgroundResource(R.drawable.ico_sgd_on);
                isFlash = false;
            } else {
                cameraManager.setFlash(true);
                flashLampBtn.setBackgroundResource(R.drawable.ico_sgd_off);
                isFlash = true;
            }
        }
    }

    /**
     * 在经过一段延迟后重置相机以进行下一次扫描。 成功扫描过后可调用此方法立刻准备进行下次扫描
     *
     * @param delayMS
     */
    public void restartPreviewAfterDelay(long delayMS) {
        if (mHandler != null) {
            mHandler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
        resetStatusView();
    }
    //==============================扫描代码结束=====================================//

    //==============================拍图代码开始=====================================//

    /**
     * 拍照
     */
    private void TakePhoto() {
        if (cameraManager.camera != null) {
            cameraManager.camera.takePicture(null, null, pictureCallback); // 拍照
        }
    }

    // 照相回调
    Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
        // @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            if (camera != null) {
                playTone();
                camera.stopPreview();
                //进行拍照保存
                try {
                    Bitmap mBitmap = BitmapUtil.rotateBitmapByDegree(byteToBitmap(data), Degrees);
                    cropimageviewRL.setVisibility(View.VISIBLE);
                    cropperLL.setVisibility(View.VISIBLE);
                    mCropImageView.setWillNotDraw(true);
                    mCropImageView.refreshDrawableState();
                    mCropImageView.setImageBitmap(mBitmap);
                    cropimageviewRL.setVisibility(View.GONE);
                    mBitmap=null;
                    //始终保存图片
//                    BitmapUtil.saveBitmapToFile(mBitmap, path);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    Log.d("log", "保存图片出错：" + e.toString());
                    ToastUtil.toast(mContext, "保存图片出错");
                }
            }
        }
    };

    // 设置拍照声音
    private void playTone() {
        MediaPlayer player = MediaPlayer.create(this, R.raw.takephoto);
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setVolume(0.5f, 0.5f);
        player.start();

    }

    /**
     * 显示要剪裁的图片
     * 这里使用Glide解决图片过大的时候不显示图片问题
     */
    private void showCutImage(final String path) {
        cropimageviewRL.setVisibility(View.VISIBLE);
        cropperLL.setVisibility(View.VISIBLE);
        mCropImageView.setWillNotDraw(true);
        mCropImageView.refreshDrawableState();
        Glide.with(this).load(new File(path)).asBitmap().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(
                new SimpleTarget<Bitmap>(Utils.getScreenWH(mContext).widthPixels, Utils.getScreenWH(mContext).heightPixels) {

                    @Override
                    public void onResourceReady(Bitmap arg0,
                                                GlideAnimation<? super Bitmap> arg1) {
                        // TODO Auto-generated method stub
                        mCropImageView.setImageBitmap(arg0);
                        cropimageviewRL.setVisibility(View.GONE);
                    }
                });
    }


    /**
     * 获取剪裁之后的图片
     */
    private void getCutImage() {
        try {
            CropperImage cropperImage = mCropImageView.getCroppedImage();
            Log.e(TAG, cropperImage.getX() + "," + cropperImage.getY());
            Log.e(TAG, cropperImage.getWidth() + "," + cropperImage.getHeight());
            Bitmap bitmap = cropperImage.getBitmap();
            BitmapUtil.saveBitmapToFile(bitmap, path);
            //图片查询
            Intent intent = new Intent(this, PhotoResultActivity.class);
            intent.putExtra("CutPath", path);
            startActivity(intent);
            finish();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            //剪裁
            Uri uri = data.getData();
            try {
                // 读取uri所在的图片
                //				Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                showCutImage(BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
            } catch (Exception e) {
                Log.e("[Android]", e.getMessage());
                Log.e("[Android]", "目录为：" + uri);
                e.printStackTrace();
            }
        }
    }

    //==============================拍图代码结束=====================================//

    // 将流转成Bitmap对象
    public Bitmap byteToBitmap(byte[] data) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap b = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        int i = 0;
        while (true) {
            if ((options.outWidth >> i <= 1000) && (options.outHeight >> i <= 1000)) {
                options.inSampleSize = 2;
                options.inJustDecodeBounds = false;
                b = BitmapFactory.decodeByteArray(data, 0, data.length, options);
                break;
            }
            i += 1;
        }
        return b;
    }

    /**
     * Byte转Bitmap
     *
     * @param b
     * @return
     */
    public Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }


    // 提供一个静态方法，用于根据手机方向获得相机预览画面旋转的角度
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static int setCameraDisplayOrientation(Activity activity,
                                                  int cameraId, Camera camera) {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);
        // 获得手机的方向
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        // 根据手机的方向计算相机预览画面应该选择的角度
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360; // 补偿镜
        } else { // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
        Degrees = result;
        Log.d("log", "旋转度：" + Degrees);
        return result;
    }

    private void startTranslation() {
        AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f);
        //设置动画持续时长
        alphaAnimation.setDuration(500);
        //设置动画结束之后的状态是否是动画的最终状态，true，表示是保持动画结束时的最终状态
        alphaAnimation.setFillAfter(true);
        //设置动画播放次数
        alphaAnimation.setRepeatCount(0);
        //开始动画
        bgRL.startAnimation(alphaAnimation);
    }

}
